/*
 * @name ajaxLib.js
 * @author : Amissah Gideon<kuulmek@yahoo.com>
 * @version 1.0
 */

Number.prototype.formatMoney = function (c, d, t) {
    var n = this, c = isNaN(c = Math.abs(c)) ? 2 : c, d = d == undefined ? "," : d, t = t == undefined ? "." : t, s = n < 0 ? "-" : "", i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "", j = (j = i.length) > 3 ? j % 3 : 0;
    return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(?=\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};

if(!Array.prototype.indexOf) {
    Array.prototype.indexOf = function(needle) {
        for(var i = 0; i < this.length; i++) {
            if(this[i] === needle) {
                return i;
            }
        }
        return -1;
    };
}


/*******************************************************************************
 *            COLLECTIONS CLASS 2.0
 ******************************************************************************/
function Collection(data) {
    this.list = {};
    this.size = 0;
    this.callbacks = {
        add:[],
        remove:[]
    };

    if (data) {
        var self = this;
        $.each(data, function (k, v) {
            self.add(k, v);
        });
    }
}

Collection.prototype.registerCallback = function (type, callback) {
    var self = this;
    if (typeof self.callbacks[type] != 'undefined') {
        self.callbacks[type].push(callback);
    }
}

Collection.prototype.fireCallbacks = function (type, key, value) {
    var self = this;
    for (var i = 0; i < self.callbacks[type].length; i++) {
        self.callbacks[type][i](key, value);
    }
}

/**
 * Adds a new object to the collection if the key for the object does not already exist
 * @param key the collection key
 * @param value the value to add
 **/
Collection.prototype.add = function (key, value) {
    var self = this;
    if (typeof self.list[key] == 'undefined') {
        self.list[key] = value;
        self.size++;

        self.fireCallbacks('add', key, value);
    }
}
/**
 * Removes the object identified by the key from the collection
 * @param key the search key
 **/
Collection.prototype.remove = function (key) {
    var self = this;
    if (typeof self.list[key] != 'undefined') {
        var value = self.list[key];
        delete self.list[key];
        self.size--;

        self.fireCallbacks('remove', key, value);
    }
}

/**
 * Returns the values stored for this key
 * @param key the search key
 **/
Collection.prototype.get = function (key) {
    var self = this;
    // if the a valid key is specified
    if (self.list.hasOwnProperty(key)) {
        return self.list[key];
    }
    // if the key specified is a number, then we may be looking for an element at a specified index
    if (!isNaN(parseInt(key))) {
        var index = 0;
        for (var k in self.list) {
            if (index == key) {
                return self.list[k];
            }
            index++;
        }
    }
    return null;
}

/**
 * Replaces or adds a new value to the map
 * @param key the key for the value
 * @param value the value to add
 */
Collection.prototype.set = function (key, value) {
    var self = this;
    self.list[key] = value;
}

/**
 * Returns the list of items stored in this collection
 * @return the list of items as an object
 */
Collection.prototype.getList = function () {
    var self = this;
    return self.list;
};

/**
 * Returns the count of the number items in this collection
 * @return number of items in this collection
 */
Collection.prototype.getSize = function () {
    var self = this;
    return self.size;
};

Collection.prototype.iterate = function (callback) {
    var self = this;
    for (var index in self.list) {
        if (typeof callback == "function") {
            callback.apply(self, [index, self.list[index]]);
        }
    }
};

Collection.prototype.getKeys = function () {
    var self = this;
    var keys = [];
    keys = Object.keys(self.list);
    return keys;
};

/**
 * Resets the list to an empty object
 */
Collection.prototype.clear = function () {
    var self = this;
    self.list = {};
}

/*******************************************************************************
 *            END OF COLLECTIONS CLASS
 ******************************************************************************/



var jLib = {
    /* Function init
     * This function is the entry point of the Object.
     * @param void
     * @return void
     * @access public
     * */
    init:function () {
        var self = this;
        $("#loader_bar").hide();
        /*Show a loading message whenever an Ajax request starts (and none is already active).*/
        $("#loader_bar").ajaxStart(function () {
            $(this).show();
        });

        $("#loader_bar").ajaxStop(function () {
            $(this).hide();
        });

        $('.all-tool-tip').tooltip();

    },

    //////////////////////Order General Functions
    array_diff:function (a1, a2) {
        var a = [], diff = [];
        for (var i = 0; i < a1.length; i++)
            a[a1[i]] = true;
        for (var i = 0; i < a2.length; i++)
            if (a[a2[i]]) delete a[a2[i]];
            else a[a2[i]] = true;
        for (var k in a)
            diff.push(k);
        return diff;
    },


    formatNumber:function($value,$type,$decimal_place){

        if(!$type){
            $type='number';
        }
        if(!$decimal_place){
            $decimal_place=2;
        }
        var rt = 0.00;
        if($type == 'money'){// Money Format
            rt =  parseFloat($value).formatMoney($decimal_place, '.', ',')
        }
        else{// Decinmal Number
            rt =  parseFloat($value).toFixed($decimal_place);
        }

        return rt;
    },


    convertDate: function ($date, $type){
        if($date.length == 0){
            return '';
        }
        var d = new Date($date);
        var $res = '';
        if($type == 'mysql'){
            $res = d.toFormattedString('yyyy-MM-dd');
        }
        else if($type == 'ui'){
            $res =  d.toFormattedString('MMMM dd, yyyy');
        }
        return $res;
    },


    message: function(title, txt, type ,callback){
        if(type == 'success'){
            cl = 'green-gradient';
        }
        else if(type == 'warning'){
            cl = 'orange-gradient';
        }
        else if(type == 'error'){
            cl = 'red-gradient';
        }
        else if(type == 'info'){
            cl = 'blue-gradient';
        }
        else{
            cl = 'red-gradient';
        }
    },

    floatOnly:function($this, event){
        // Backspace, tab, enter, end, home, left, right,decimal(.)in number part, decimal(.) in alphabet
        // We don't support the del key in Opera because del == . == 46.
        var controlKeys = [8, 9, 13, 35, 36, 37, 39,110,190];
        // IE doesn't support indexOf
        var isControlKey = controlKeys.join(",").match(new RegExp(event.which));
        // Some browsers just don't raise events for control keys. Easy.
        // e.g. Safari backspace.
        if (!event.which || // Control keys in most browsers. e.g. Firefox tab is 0
            (49 <= event.which && event.which <= 57) || // Always 1 through 9
            (96 <= event.which && event.which <= 106) || // Always 1 through 9 from number section
            (48 == event.which && $this.attr("value")) || // No 0 first digit
            (96 == event.which && $this.attr("value")) || // No 0 first digit from number section
            isControlKey) { // Opera assigns values for control keys.
            return;
        } else {
            event.preventDefault();
        }
    },


    /*Universal Delete for all Main record DataTable*/
    do_delete:function (url, grid, callback) {
        var self = this;
        var row_ids = FlexObject.getSelectedRowIds(grid);
        //console.log(row_ids);
        var r=confirm("Are you sure you want to continue ?");
        if (r==true){
            $.post(url, {'ids[]': row_ids},function(response){
                //delete was successful, remove checkbox rows
                if(response.code == 0){
                    FlexObject.removeGridRows(grid);
                    alert(response.msg);
                    if(typeof callback == 'function'){
                        callback();
                    }
                }
                else if(response.code == 1){
                    alert(response.msg);
                }
            },"json");
        }
    },

    /*Universal Delete for all Main record DataTable*/
    do_sub_delete:function (url, grid, callback) {
        var self = this;
        var row_ids = FlexObject.getSelectedSubRowIds(grid);

        var r=confirm("Are you sure you want to continue ?");
        if (r==true){
            $.post(url, {'ids[]': row_ids},function(response){
                //delete was successful, remove checkbox rows
                if(response.code == 0){
                    FlexObject.removeSubGridRows(grid);
                    alert(response.msg);
                    if(typeof callback == 'function'){
                        callback();
                    }
                }
                else if(response.code == 1){
                    alert(response.msg);
                }
            },"json");
        }
    }
};

/* when the page is loaded */
$(document).ready(function () {
    //Hiding the loader bar
    jLib.init();
});